/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

import hero.client.test.SimpleCallbackHandler;
import hero.interfaces.BnNodeValue;
import hero.interfaces.ProjectSession;
import hero.interfaces.ProjectSessionHome;
import hero.interfaces.ProjectSessionUtil;
import hero.interfaces.UserRegistration;
import hero.interfaces.UserRegistrationHome;
import hero.interfaces.UserRegistrationUtil;
import hero.interfaces.UserSession;
import hero.interfaces.UserSessionHome;
import hero.interfaces.UserSessionUtil;
import hero.util.HeroException;
import java.io.IOException;
import java.io.PrintWriter;
import java.rmi.RemoteException;
import java.util.Collection;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.CreateException;
import javax.naming.NamingException;
import javax.security.auth.login.LoginContext;
import javax.security.auth.login.LoginException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author Larry
 */
public class CambiarUsuario extends HttpServlet {

    private UserSession usrSession;
    private UserRegistration usrReg;
    private ProjectSession prjSession;
    private String modelo = "PruebaPerformerAssigment";

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        String instancia;
        try {
            instancia = request.getParameter("instancia");
            if (instancia != null) {
                exampleUno(instancia);
            } else {
                out.println("Please pass the 'instancia' parameter");
            }
        } finally {
            out.close();
        }
    }

    public void exampleUno(String nombreInstancia) {
        String nombreActividad = "Actividad02";
        BnNodeValue actividad;
        Collection usuarios;
        try {
            String strUsuario = "lbeltran";
            char[] strContrasena = {'1', '2', '3'};
            autentica(strUsuario, strContrasena);
            //String nombre_instancia = prjSession.instantiateProject(modelo);
            prjSession.initProject(nombreInstancia);
            actividad = usrSession.getNode(nombreInstancia, nombreActividad);
            System.out.println("actividad.activityPerformerHasBeenSet()" + actividad.activityPerformerHasBeenSet());
            System.out.println("actividad.getExecutor():" + actividad.getExecutor());
            actividad.setActivityPerformer("lrivas");

            System.out.println("actividad.getActivityPerformer(): " + actividad.getActivityPerformer());
            System.out.println("actividad.getBnRole().getName():" + actividad.getBnRole().getName());
            if (prjSession.getNodePerformerAssign(nombreActividad) != null) {
                System.out.println("prjSession.getNodePerformerAssign(actividad): " + prjSession.getNodePerformerAssign(nombreActividad));
                System.out.println("prjSession.getNodePerformerAssign(nombreActividad).getName():" + prjSession.getNodePerformerAssign(nombreActividad).getName());

            }

            System.out.println("Todos los usuarios de bonita");
            usuarios = prjSession.getAllUsers();
            for (Object obj : usuarios) {
                System.out.println("usuario:" + obj);
            }
            System.out.println("");

            autentica("bsoa", "bsoa".toCharArray());
            prjSession.initProject(nombreInstancia);
            System.out.println("Agreagamos el nuevo usuario a " + prjSession.getName());
            prjSession.addUser("ccorral");


            autentica(strUsuario, strContrasena);
            prjSession.initProject(nombreInstancia);

            System.out.println("Usuarios del proyecto");
            usuarios = prjSession.getUsers();
            for (Object obj : usuarios) {
                System.out.println("usuario:" + obj);
            }
            System.out.println("");

            autentica("bsoa", "bsoa".toCharArray());
            prjSession.initProject(nombreInstancia);
            System.out.println("Asociamos a ccorral al rol:" + actividad.getBnRole().getName());
            prjSession.setUserRole("ccorral", actividad.getBnRole().getName());

            autentica(strUsuario, strContrasena);
            prjSession.initProject(nombreInstancia);
            System.out.println("Usuarios con el rol: " + actividad.getBnRole().getName());
            usuarios = prjSession.getUsersRole(actividad.getBnRole().getName());
            for (Object obj : usuarios) {
                System.out.println("usuario:" + obj);
            }
            System.out.println("");

        } catch (HeroException ex) {
            Logger.getLogger(CambiarUsuario.class.getName()).log(Level.SEVERE, null, ex);
        } catch (RemoteException ex) {
            Logger.getLogger(CambiarUsuario.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public boolean autentica(String strUsuario, char[] strContrasena) {
        SimpleCallbackHandler handler = new SimpleCallbackHandler(strUsuario, strContrasena);
        LoginContext lc;
        try {
            lc = new LoginContext("Test02", handler);
            lc.login();
            ProjectSessionHome prjHome = (ProjectSessionHome) ProjectSessionUtil.getHome();
            UserRegistrationHome userRHome = (UserRegistrationHome) UserRegistrationUtil.getHome();
            UserSessionHome usrHome = (UserSessionHome) UserSessionUtil.getHome();
            prjSession = prjHome.create();
            usrReg = userRHome.create();
            usrSession = usrHome.create();
            return true;
        } catch (LoginException ex) {
            ex.printStackTrace();
        } catch (RemoteException ex) {
            ex.printStackTrace();
        } catch (CreateException ex) {
            ex.printStackTrace();
        } catch (NamingException ex) {
            ex.printStackTrace();
        }
        return false;

    }
    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">

    /**
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
